package cn.ycc1.boot3tx.service.impl;

import cn.ycc1.boot3tx.domain.Book;
import cn.ycc1.boot3tx.domain.dto.BuyBookDTO;
import cn.ycc1.boot3tx.service.AccountService;
import cn.ycc1.boot3tx.service.BookService;
import cn.ycc1.boot3tx.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @author ycc
 * @date 2024/12/17
 */
@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {
    private final BookService bookService;
    private final AccountService accountService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void buy(BuyBookDTO buyBookDTO) {
        // 校验书籍是否存在
        Book book = bookService.getById(buyBookDTO.getBookId());
        if(book == null) {
            throw new RuntimeException("书籍不存在");
        }
        BigDecimal amount = book.getPrice().multiply(new BigDecimal(buyBookDTO.getQuantity()));

        // 扣减余额
        // accountService.decreaseBalance(buyBookDTO.getUserId(), amount);
        bookService.decreaseBalance(buyBookDTO.getUserId(), amount);
        // 扣减库存
        bookService.decreaseStock(buyBookDTO.getBookId(), buyBookDTO.getQuantity());
    }
}
